<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPer(1, '0')">添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type === 1" type="text" @click="addPer(2, scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPerHander(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delPerHander(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 添加权限弹窗 -->
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog :title="isedit ? '编辑权限点' : '新增权限点'" :visible="roleshowDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="addorEdit">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 树形数据处理
import { tranListToTreeData } from '@/utils/index'

// 获取权限列表和添加权限
import { getPermissionList, addPermission, updatePermission, getPermissionDetail, delPermission } from '@/api/permission'
export default {
  data() {
    // 两种校验规则,不允许同名和同值
    const validName = (rule, value, callback) => {
      // 添加判断重名
      let existNameList = this.originList
        .filter(item => item.pid === this.formData.pid)
        .map(item => item.name)
      // 编辑判断重名
      if (this.isedit) {
        existNameList = this.originList
          .filter(
            item =>
              item.pid === this.formData.pid && item.id !== this.formData.id
          )
          .map(item => item.name)
      }
      existNameList.includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    const validCode = (rule, value, callback) => {
      // 添加判断重复权限标识
      let existCodeList = this.originList
      // 编辑判断重复权限标识
      if (this.isedit) {
        existCodeList = this.originList.filter(
          item => item.id !== this.formData.id
        )
      }
      existCodeList.map(item => item.code).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    return {
      roleshowDialog: false, // 添加权限弹窗的显示与隐藏
      permissionList: [], // 权限管理列表数据
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      isedit: false,
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      },
      originList: {}
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 点击提交按钮,分辨是添加还是编辑
    async addorEdit() {
      this.$refs.perForm.validate(async valid => {
        if (valid) {
          this.isedit ? this.EditPermissions() : this.AddPermissions()
        }
      })
    },
    // 编辑,保存到后端
    async EditPermissions() {
      const res = await updatePermission(this.formData)
      this.$message.success(res.message)
      this.getPermissionList()
      this.roleshowDialog = false
    },
    // 添加,保存到后端
    async AddPermissions() {
      const res = await addPermission(this.formData)
      this.$message.success(res.message)
      this.getPermissionList()
      this.roleshowDialog = false
    },
    // 点击编辑数据回显,
    async editPerHander(id) {
      this.isedit = true
      if (this.isedit) {
        this.roleshowDialog = true
        const res = await getPermissionDetail(id)
        this.formData = res.data
      }
    },
    // 点击两个添加按钮 ,出入不同的type 和 id ,
    addPer(type, id) {
      this.isedit = false
      this.roleshowDialog = true
      // 记录当前添加的关键信息
      this.formData.type = type
      this.formData.pid = id
    },
    async getPermissionList() {
      const res = await getPermissionList()
      this.originList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name: name.trim(), code }))
      this.permissionList = tranListToTreeData(res.data, '0')
    },
    // 点击取消关闭添加权限弹窗
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 标识
        description: '', // 描述
        type: '', // 类型 该类型 不需要显示 因为点击添加的时候已经知道类型了
        pid: '', // 因为做的是树 需要知道添加到哪个节点下了
        enVisible: '0' // 开启
      }
      // 重置弹出层表单的数据
      this.$refs.perForm.resetFields()
      this.roleshowDialog = false
      this.isedit = false
    },
    // 实现删除功能
    async delPerHander(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async err => {
        if (err === 'confirm') {
          const res = await delPermission(id)
          this.$message.success(res.message)
          this.roleshowDialog = false
          this.getPermissionList()
        }
      }).catch(err => {
        if (err === 'cancel') {
          this.$message('你已经取消删除了')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
